namespace ETestIT.Data
{
    using System.Collections.Generic;
    using Core;
    using Core.DataInterfaces;
    using NHibernate.Criterion;
    using NHibernate.Transform;
    using SharpArch.Data.NHibernate;
    using ETestIT.Core.Infrastructure;

    public class CandidateResumeRepository : Repository<CandidateResume>, ICandidateResumeRepository
    {
        public IList<CandidateResume> GetLatestVersions(int candidateId)
        {
            var resumes = new Dictionary<int, CandidateResume>();

            var candidateResumes = Session.CreateCriteria<CandidateResume>()
                .CreateAlias("TheCandidate", "candidate")
                .Add(Restrictions.Eq("candidate.Id", candidateId))
                .SetResultTransformer(new DistinctRootEntityResultTransformer())
                .List();

            foreach (CandidateResume candidateResume in candidateResumes)
            {
                var resume = candidateResume.TheResume;
                var jobTitleId = candidateResume.TheJobTitle.Id;

                if ((!resumes.ContainsKey(jobTitleId)) ||
                    (resumes[jobTitleId].TheResume.Version < resume.Version))
                    resumes[jobTitleId] = candidateResume;
            }

            return new List<CandidateResume>(resumes.Values);
        }

        public CandidateResume GetByResumeId(int resumeResumeId)
        {
            return Session.CreateCriteria<CandidateResume>()
                .CreateAlias("TheResume", "resume")
                .Add(Restrictions.Eq("resume.Id", resumeResumeId))
                .SetResultTransformer(new DistinctRootEntityResultTransformer())
                .UniqueResult<CandidateResume>();
        }

        public IList<Resume> GetResumesHistoryBy(int candidateResumeId)
        {
            var resumes = new List<Resume>();

            var candidateResume = Get(candidateResumeId);

            var candidateResumes = Session.CreateCriteria<CandidateResume>()
                .CreateAlias("TheCandidate", "candidate")
                    .Add(Restrictions.Eq("candidate.Id", candidateResume.TheCandidate.Id))
                .CreateAlias("TheJobTitle", "jobTitle")
                    .Add(Restrictions.Eq("jobTitle.Id", candidateResume.TheJobTitle.Id))
                .SetResultTransformer(new DistinctRootEntityResultTransformer())
                .List<CandidateResume>();

            candidateResumes.ForEach(x => resumes.Add(x.TheResume));

            return resumes;
        }
    }
}